package com.xiaoluo.service;

import com.xiaoluo.cd.dao.SysUserMapper;
import com.xiaoluo.cd.entity.base.SysUser;
import com.xiaoluo.cd.entity.base.SysUserExample;
import com.xiaoluo.web.form.SysUserForm;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Project : XL-CD
 * Package : com.xiaoluo.service
 * Created by Willian.
 * Date  : 2016/1/15 11:38.
 */
@Service
@Transactional
public class UserService {

    @Autowired
    private SysUserMapper userMapper;

    public SysUserForm get(Long id){

        SysUserForm result = new SysUserForm();
        SysUser user = userMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(user,result);
        return result;
    }
    /**
     *
     * @param userName
     * @return
     */
    public SysUserForm find(String userName){

        SysUserExample example = new SysUserExample();
        example.createCriteria().andUserNameEqualTo(userName);

        List<SysUser> list = userMapper.selectByExampleWithBLOBs(example);
        if(list != null && list.size() >0){
            SysUserForm result = new SysUserForm();
            SysUser user = list.get(0);
            BeanUtils.copyProperties(user,result);
            return result;
        }

        return null;
    }

    /**
     *
     * @param user
     */
    public void save(SysUserForm user){

        SysUser temp = find(user.getUserName());

        if(user.getId() == null){
            if(temp != null) return;

            user.setCreateAt(new Date());
            userMapper.insert(user);
        }else {
            if(!user.getId().equals(temp.getId()))
                return;

            user.setUpdateAt(new Date());
            userMapper.updateByPrimaryKeyWithBLOBs(user);
        }
    }



    /**
     *
      * @return
     */
    public List<SysUser> list(){
        return userMapper.selectByExample(null);
    }

}
